﻿#region USING SYSTEM

using System.Collections.Generic;
using YunSpace.Core;
using YunSpace.Data;
using YunSpace.Domain.Entity.WorkFlow;
using YunSpace.Domain.IRepository.WorkFlow;
using YunSpace.Domain.ViewModel.WorkFlow;

#endregion

namespace YunSpace.Repository.WorkFlow
{
    public class WorkFlowRepository : RepositoryBase<WorkFlowEntity>, IWorkFlowRepository
    {
        public List<FlowManageDto> GetFlowManages(Pagination pagination)
        {
            var sqlStr = @"
                    SELECT wf.F_Id AS F_WorkFlowId, wf.F_WorkFlowName, wf.F_CreatorTime, wf.F_WorkFormId,
                        u.F_RealName AS F_Creator, 
                        (
                            SELECT COUNT(1)
                            FROM Sys_WorkFlowDetail AS d
                            WHERE d.F_WorkFlowId = wf.F_Id AND (d.F_DeleteMark IS NULL OR d.F_DeleteMark <> 1)
                         ) AS F_WorkFlowDetailCount
                    FROM Sys_WorkFlow AS wf
                    INNER JOIN Sys_User AS u ON u.F_Id = wf.F_CreatorUserId
                    WHERE wf.F_DeleteMark IS NULL OR wf.F_DeleteMark <> 1";

            pagination.records = GetFlowManagerViewModelCount();

            var startNo = pagination.rows * (pagination.page - 1);
            var endNo = startNo + pagination.rows;

            sqlStr = $"{sqlStr} ORDER BY wf.{pagination.sidx} LIMIT {startNo},{endNo};";

            using (var db = new RepositoryBase())
            {
                var result = db.FindList<FlowManageDto>(sqlStr);
                return result;
            }
        }

        private int GetFlowManagerViewModelCount()
        {
            const string sql = @"SELECT COUNT(1)
                        FROM Sys_WorkFlow AS wf
                        INNER JOIN Sys_User AS u ON u.F_Id = wf.F_CreatorUserId
                        WHERE wf.F_DeleteMark IS NULL OR wf.F_DeleteMark <> 1;";

            return Count(sql);
        }

        
    }
}